package edu.cuit.avatar.type;

import edu.cuit.avatar.enums.Gender;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/29 8:58
 */
public class GenderTypeHandler implements TypeHandler<Gender> {
    /**
     * 设置预编译语句?参数值(将Gender类型转为jdbc类型对应的数据表字段所对应的类型)
     * @param ps 预编译语句对象
     * @param i 参数索引
     * @param parameter 参数值
     * @param jdbcType jdbc type
     * @throws SQLException
     */
    @Override
    public void setParameter(PreparedStatement ps, int i, Gender parameter, JdbcType jdbcType) throws SQLException {
        if(parameter != null) {
            ps.setString(i, parameter.getValue());
        }
    }

    /**
     * 结果集映射,将结果集中对应的字段映射为Gender类型
     * @param rs 结果集
     * @param columnName 列名
     * @return Gender
     * @throws SQLException
     */
    @Override
    public Gender getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return "男".equals(value) ? Gender.MALE : Gender.FEMALE;
    }

    @Override
    public Gender getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return "男".equals(value) ? Gender.MALE : Gender.FEMALE;
    }

    /**
     * 存储过程输出参数(结果) 类型的映射
     * "男" -----> Gender.MALE
     * @param cs CallableStatement
     * @param columnIndex 参数索引
     * @return
     * @throws SQLException
     */
    @Override
    public Gender getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return "男".equals(value) ? Gender.MALE : Gender.FEMALE;
    }
}
